#!/bin/bash --norc

if [ "$LOGNAME" != "root" ]; then
    echo "You need to run $0 through sudo"
    exit 1
fi

if [ -x /usr/sbin/daemonize ]; then
    DAEMONIZE=/usr/sbin/daemonize
elif [ -x /usr/bin/daemonize ]; then
    DAEMONIZE=/usr/bin/daemonize
else
    echo "Cannot execute daemonize to start systemd."
    exit 1
fi

if ! command -v /lib/systemd/systemd > /dev/null; then
    echo "Cannot execute /lib/systemd/systemd."
    exit 1
fi

if ! command -v /usr/bin/unshare > /dev/null; then
    echo "Cannot execute /usr/bin/unshare."
    exit 1
fi

SYSTEMD_EXE="/lib/systemd/systemd --unit=basic.target"

if [ -f /etc/systemd/system/wsl-k8s.target ];then
  if [ "${WSL_DISTRO_NAME}" = 'wsl-k8s' ];then
    SYSTEMD_EXE="/lib/systemd/systemd --unit=wsl-k8s.target"
  fi
fi

SYSTEMD_PID="$(ps -eo pid=,args= | awk '$2" "$3=="'"$SYSTEMD_EXE"'" {print $1}')"
if [ -z "$SYSTEMD_PID" ]; then

    WSL2_IP=$(ip addr | grep eth0 | grep inet | cut -d ' ' -f 6 | cut -d '/' -f 1)

    if [ -z "$WSL2_IP" ];then
       exit 1
    fi

    mkdir -p /etc/systemd/system.conf.d/
    {
      echo "[Manager]";
      echo "DefaultEnvironment=WSL2_IP=${WSL2_IP}";
    } | tee /etc/systemd/system.conf.d/99-wsl.conf > /dev/null

    {
      echo "export WSL2_IP=${WSL2_IP}";
    } | tee /etc/profile.env > /dev/null

    chmod +x /etc/profile.env || true

    WINDOWS_IP=$(cat /etc/resolv.conf | grep nameserver | cut -d ' ' -f 2)

    echo "$WSL2_IP wsl2 wsl2.k8s.khs1994.com" >> /etc/hosts
    echo "$WINDOWS_IP windows.k8s.khs1994.com" >> /etc/hosts

    "$DAEMONIZE" /usr/bin/unshare --fork --pid --mount-proc bash -c 'export container=wsl; mount -t binfmt_misc binfmt_misc /proc/sys/fs/binfmt_misc; exec '"$SYSTEMD_EXE"
    while [ -z "$SYSTEMD_PID" ]; do
        echo "Sleeping for 1 second to let systemd settle"
        sleep 1
        SYSTEMD_PID="$(ps -eo pid=,args= | awk '$2" "$3=="'"$SYSTEMD_EXE"'" {print $1}')"
    done
fi

USER_HOME="$(getent passwd | awk -F: '$1=="'"$SUDO_USER"'" {print $6}')"
if [ -n "$SYSTEMD_PID" ] && [ "$SYSTEMD_PID" != "1" ]; then
    if [ -n "$1" ] && [ "$1" != "bash --login" ] && [ "$1" != "/bin/bash --login" ]; then
        exec /usr/bin/nsenter -t "$SYSTEMD_PID" -a \
            /usr/bin/sudo -H -u "$SUDO_USER" \
            /bin/bash -c 'set -a; [ -f "$HOME/.systemd-env" ] && source "$HOME/.systemd-env"; set +a; exec bash -c '"$(printf "%q" "$@")"
    else
        exec /usr/bin/nsenter -t "$SYSTEMD_PID" -a \
            /bin/login -p -f "$SUDO_USER" \
            $([ -f "$USER_HOME/.systemd-env" ] && /bin/cat "$USER_HOME/.systemd-env" | xargs printf ' %q')
    fi
    echo "Existential crisis"
    exit 1
fi
